package com.atguigu.blob;

import com.atguigu.utils.DBUtils;
import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 测试使用PrepearedStatment操作Blob类型的数据
 *      错误：Error reading from InputStream java.io.IOException
 *
 * @author hjwStrart
 * @time 2022-03-07 19:42
 */
public class BlobTest {
    public static void main(String[] args) {
        String sql = "insert into customers values(null,'test','test@qq.com','2020-2-2',?); ";
        Connection conn = null;
        PreparedStatement ps = null;
        BufferedInputStream bis = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=UTC","root","hjw123..");
            ps = conn.prepareStatement(sql);
//     void setBlob(int parameterIndex, InputStream inputStream)
            InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("img/login.jpg");
            bis = new BufferedInputStream(is);
            ps.setBlob(1, bis);
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
